import json

from django.core.cache import caches
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin


class UserAgentMiddleware(MiddlewareMixin):
    """
    Middleware that handles temporary messages.
    """

    def process_request(self, request):
        print(f"UserAgentMiddleware处理请求")
        pass

    def process_response(self, request, response):
        print(f"UserAgentMiddleware处理响应")
        print(f"检测到请求工具", request.headers['User-Agent'])
        if request.headers['User-Agent'] not in [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",

        ]:
            return HttpResponse("出错了")


        return response

# Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/12
# 9.0.0.0 Safari/537.36


class ForbiddenIPMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print(f"UserAgentMiddleware处理请求")
        pass

    def process_response(self, request, response):
        print(f"ForbiddenIPMiddleware处理响应")
        cache = caches["redis"]

        # 将需要封禁的ip加入数据库
        fbs_ips = []
        fbs_ips.append(request.META.get("REMOTE_ADDR"))
        cache.set("ips", json.dumps(fbs_ips))


        fbs_ips = cache.get("ips")
        fbs_ips = json.loads(fbs_ips)

        current_ip = request.META.get("REMOTE_ADDR")
        if current_ip in fbs_ips:
            return HttpResponse("出错了")

        return response